package com.kly.user.task.v2;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.NetUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.user.db.dao.ChatterWorkSettingDao;
import com.kly.user.db.dao.UserChatterMappingDao;
import com.kly.user.db.dao.UserMessageReportDao;
import com.kly.user.db.dao.UserMessageTotalReportDao;
import com.kly.user.db.dbo.UserMessageReportDBO;
import com.kly.user.db.entity.ChatterWorkSettingEntity;
import com.kly.user.db.entity.UserChatterMappingEntity;
import com.kly.user.db.entity.UserMessageReportEntity;
import com.kly.user.db.entity.UserMessageTotalReportEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 消息回复率统计任务
 */
@Component
public class MessageStatusStatisticalTask {

    private static Log logger = LogFactory.getLog(MessageStatusStatisticalTask.class);

    @Resource
    UserMessageReportDao userMessageReportDao;
    @Resource
    UserMessageTotalReportDao userMessageTotalReportDao;
    @Resource
    UserChatterMappingDao userChatterMappingDao;
    @NacosValue(value = "${default.reply.times:300}", autoRefreshed = true)
    private Long defaultReplyTimes;
    @NacosValue(value = "${reply.on.times:60}", autoRefreshed = true)
    private Long replyOnTimes;
    @NacosValue(value = "${testSessionId:ea8b92884cc082711a934946ba426290}", autoRefreshed = true)
    private String testSessionId;
    @NacosValue(value = "${test.flag:false}", autoRefreshed = true)
    private Boolean testFlag;
    @Resource
    ChatterWorkSettingDao chatterWorkSettingDao;
    /**
     * 任务IP限制
     */
    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;
    /**
     * 任务启停开关
     */
    @NacosValue(value = "${enable.message.statistical.switch:true}", autoRefreshed = true)
    private Boolean enableMessageStatisticalSwitch;

    private String localIP = NetUtil.getLocalhostStr();

    /**
     * 每10分钟统计一次
     */
    @Scheduled(fixedDelay = 1000 * 600)
    public void sumUserMsgReport() {
        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============NotTaskJobExecutor, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }
        if (!enableMessageStatisticalSwitch) {
            logger.info("=============NotTaskJobExecutor, enableFlashchatSwitch:{}", enableMessageStatisticalSwitch);
            return;
        }

        final DateTime todayBeginning = DateUtil.beginOfDay(new Date());

        final List<UserChatterMappingEntity> allChatters = userChatterMappingDao.selectAllChatters();
        final List<String> allChatterAccounts = getAllChatterAccounts(allChatters);
        if (allChatterAccounts == null) {
            return;
        }


        // 获取chatter工作时间
        final List<ChatterWorkSettingEntity> settingsByChatterCods = chatterWorkSettingDao.getSettingsByChatterCods(getAllChatterUserCodes(allChatters));

        final List<UserMessageReportEntity> sumUserMsgReports = userMessageReportDao.sumUserMsgReport(todayBeginning);
        if (CollectionUtils.isEmpty(sumUserMsgReports)) {
            return;
        }

        // 更新汇总表中的数据
        userMessageReportDao.removeTodaySumReport(todayBeginning );
        for (UserMessageReportEntity entity : sumUserMsgReports) {
            final ChatterWorkSettingEntity chatterWorkSetting = settingsByChatterCods.parallelStream().filter(o -> o.getUserCode().equals(entity.getChatterUserCode())).findAny().orElse(null);
            entity.setInWorktimeFlag(0);
            if (chatterWorkSetting != null && (entity.getCreateHour() >= chatterWorkSetting.getStartHour() && entity.getCreateHour() < chatterWorkSetting.getEndHour() || entity.getCreateHour() >= chatterWorkSetting.getStartHour2() && entity.getCreateHour() < chatterWorkSetting.getEndHour2())) {
                entity.setInWorktimeFlag(1);
            }
            final UserChatterMappingEntity chatter = getByChatterUserCode(allChatters, entity.getChatterUserCode());
            if (chatter != null) {
                entity.setChatterAccount(chatter.getChatterAccount());
                entity.setChatterNickName(chatter.getChatterNickName());
            }
            userMessageReportDao.insert(entity);
        }

        // 更新当日汇总表数据
        storeReplyTotalData(todayBeginning);


    }

    private void storeReplyTotalData(Date todayBeginning) {

        final UserMessageReportDBO userMessageReportDbo = userMessageReportDao.sumTodayReport();
        if (userMessageReportDbo != null) {
            UserMessageTotalReportEntity todayReplyReport = userMessageTotalReportDao.getTodayReplyReport();
            todayReplyReport = todayReplyReport == null ? new UserMessageTotalReportEntity() : todayReplyReport;
            todayReplyReport.setActiveSessionNum(userMessageReportDbo.getActiveSessionTotal());
            todayReplyReport.setReceiveMessageNum(userMessageReportDbo.getReceivedMessageNum());
            todayReplyReport.setReplyNum(userMessageReportDbo.getReplyNum());
            todayReplyReport.setReplyOnTimeNum(userMessageReportDbo.getReplyOnTimeMessageNum());
            todayReplyReport.setCreateDt(todayBeginning);

            if (todayReplyReport.getId() == null) {
                userMessageTotalReportDao.insert(todayReplyReport);
            } else {
                userMessageTotalReportDao.updateByPrimaryKey(todayReplyReport);
            }
        }
    }



    private List<String> getAllChatterAccounts(List<UserChatterMappingEntity> allChatters) {
        if (CollectionUtils.isEmpty(allChatters)) {
            return null;
        }
        return allChatters.parallelStream().map(UserChatterMappingEntity::getChatterAccount).filter(Objects::nonNull).distinct().collect(Collectors.toList());
    }


    private List<String> getAllChatterUserCodes(List<UserChatterMappingEntity> allChatters) {
        if (CollectionUtils.isEmpty(allChatters)) {
            return null;
        }
        return allChatters.parallelStream().map(UserChatterMappingEntity::getChatterUserCode).filter(Objects::nonNull).distinct().collect(Collectors.toList());
    }

    private UserChatterMappingEntity getByChatterUserCode(List<UserChatterMappingEntity> allChatters, final String chatterUserCode) {
        if (CollectionUtils.isEmpty(allChatters)) {
            return null;
        }
        return allChatters.parallelStream().filter(o -> o.getChatterUserCode().equals(chatterUserCode)).findAny().orElse(null);
    }


}
